package com.example.javaserve.utils;

import org.springframework.stereotype.Component;

/**
 * @projectName: my_project
 * @package: com.example.javaserve.utils
 * @className: FileUtil
 * @author: xxXPCSC
 * @description: TODO
 * @date: 2024/1/5 18:42
 * @version: 1.0
 **/
@Component
public class FileUtil {
    public  String getRealFilename(String fileName){
        if(fileName.indexOf("-")==-1)
            return fileName;
        String result = fileName.substring(fileName.indexOf('-')+1);
        return  result;
    }

    public  String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf(".");
        if (lastDotIndex != -1 && lastDotIndex < fileName.length() - 1) {
            return fileName.substring(lastDotIndex + 1);
        }
        return "";
    }

    public  boolean isImageFile(String fileExtension) {
        String[] imageExtensions = {"jpg", "jpeg", "png", "gif"};
        for (String extension : imageExtensions) {
            if (extension.equalsIgnoreCase(fileExtension)) {
                return true;
            }
        }
        return false;
    }

    public  boolean isExcelFile(String fileExtension) {
        String[] excelExtensions = {"xls", "xlsx"};
        for (String extension : excelExtensions) {
            if (extension.equalsIgnoreCase(fileExtension)) {
                return true;
            }
        }
        return false;
    }

    public  boolean isWordFile(String fileExtension) {
        String[] wordExtensions = {"doc", "docx"};
        for (String extension : wordExtensions) {
            if (extension.equalsIgnoreCase(fileExtension)) {
                return true;
            }
        }
        return false;
    }

    public  String getFileSize(double fileSizeInBytes){
        String fileSize = String.format("%.2f",fileSizeInBytes) + "Byte";
        if (fileSizeInBytes >= 1024 * 1024 * 1024) {
            double fileSizeInGB = (double) fileSizeInBytes / (1024 * 1024 * 1024);
            fileSize = String.format("%.2f",fileSizeInGB) + "GB";
        } else if (fileSizeInBytes >= 1024 * 1024) {
            double fileSizeInMB = (double) fileSizeInBytes / (1024 * 1024);
            fileSize = String.format("%.2f",fileSizeInMB) + "MB";

        } else {
            double fileSizeInKB = (double) fileSizeInBytes / 1024;
            fileSize = String.format("%.2f",fileSizeInKB) + "KB";
        }
        return fileSize;
    }
}
